package com.example.ioc_application;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.ioc_application.consts.ApiConst;
import com.example.ioc_application.service.Dht11Service;
import com.example.ioc_application.utils.HttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity implements ServiceConnection {

    private Button openLedButton;

    private Button closeLedButton;

    private Button openMotorButton;

    private Button closeMotorButton;

    private TextView dht11Text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        openLedButton = findViewById(R.id.openLedBtn);
        openLedButton.setOnClickListener((v) -> {
            asyncSendHttpRequest(ApiConst.OPEN_LED);
        });
        closeLedButton = findViewById(R.id.closeLedBtn);
        closeLedButton.setOnClickListener((v) -> {
            asyncSendHttpRequest(ApiConst.CLOSE_LED);
        });
        openMotorButton = findViewById(R.id.openMotorBtn);
        openMotorButton.setOnClickListener((v) -> {
            asyncSendHttpRequest(ApiConst.OPEN_MOTOR);
        });
        closeMotorButton = findViewById(R.id.closeMotorBtn);
        closeMotorButton.setOnClickListener((v) -> {
            asyncSendHttpRequest(ApiConst.CLOSE_MOTOR);
        });
        dht11Text = findViewById(R.id.dht11);
        bindService(new Intent(this, Dht11Service.class), this, BIND_AUTO_CREATE);
    }

    /**
     * 异步执行http请求
     *
     * @param apiUrl 接口地址，省略前面的基础url
     */
    private void asyncSendHttpRequest(String apiUrl) {
        new Thread(() -> {
            JSONObject json = null;
            try {
                json = new JSONObject(HttpUtils.send(apiUrl));
                Log.d("JSONObject", json.toString());
                Looper.prepare();
                Toast.makeText(MainActivity.this, json != null ? json.getString("data") : "网络错误", Toast.LENGTH_SHORT).show();
                Looper.loop();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }).start();
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        if (service instanceof Dht11Service.Binder) {
            Dht11Service.Binder binder = (Dht11Service.Binder) service;
            Dht11Service dht11Service = binder.getService();
            dht11Service.setCallback((json) -> {
                final String temperature = "temperature";
                final String humidity = "humidity";
                JSONObject data = json.getJSONObject("data");
                Message message = new Message();
                // 转义符号为%
                message.obj = String.format("温度:%.1f℃ 湿度:%.1f%%RH", data.getDouble(temperature), data.getDouble(humidity));
                dht11TextHandler.sendMessage(message);
            });
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }

    /**
     * 处理视图的变化
     */
    private Handler dht11TextHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            dht11Text.setText(msg.obj.toString());
        }
    };
}